﻿using System;
using System.Web;
using MyLib.IO;
using MyLib.Web.Properties;
using log4net;

namespace MyLib.Web.HttpHandlers {
	/// <summary>
	/// 
	/// </summary>
	public class UploadHandler : System.Web.IHttpAsyncHandler {
		/// <summary>
		/// Internal logger.
		/// </summary>
		private ILog m_logger = LogManager.GetLogger(typeof(UploadHandler));

		#region IHttpHandler Members

		/// <summary>
		/// 
		/// </summary>
		public bool IsReusable {
			get { return true; }
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="cb"></param>
		/// <param name="extraData"></param>
		/// <returns></returns>
		public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {
			Action func = () => {
				ProcessRequest(context);
			};

			return func.BeginInvoke(cb, extraData);

		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="result"></param>
		public void EndProcessRequest(IAsyncResult result) {
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		public void ProcessRequest(HttpContext context) {
			var fc = 0;
			var sessionId = context.Request["session_id"];
			for (int i = 0; i < context.Request.Files.Count; ++i) {
				var file = context.Request.Files[i];
				if (file == null) {
					continue;
				}
				m_logger.DebugFormat("Session id: {0}, Upload file: {1}, Size = {2}", 
					sessionId,
					file.FileName, file.ContentLength);

				System.Threading.Thread.Sleep(5000);

				++fc;
			}

			context.Response.ContentEncoding = System.Text.Encoding.UTF8;
			context.Response.ContentType = "text/plain";
			context.Response.Write(fc);

			context.Response.End();
		}

		#endregion
	} // end of FileHandler.
}
